﻿using BackendLogic.BaseLogic;
using ComTools.EnumHelper;
using ComTools.Mapping;
using LogicModel.DataModel;
using MappingDTO.Admin;
using MSSQL.CommandTool;
using MSSQL.Enums;
using System.Collections.Generic;
using ToolsModel;

namespace BackendLogic
{
    /// <summary>
    /// 菜单管理
    /// </summary>
    public class SysMenuServiceImpl : BaseLogicService, ISysMenuService
    {
        /// <summary>
        /// 获取角色可操作菜单
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<IList<SysMenuRetDTO>> LoadMenus()
        {
            var result = new ResultJsonInfo<IList<SysMenuRetDTO>>();
            var loginUser = UserSession.GetLoginUser();
            query.DataBaseName = DatabaseName.GeneralFrameworkDB.GetEnumItemDescription();

            string sRoleCodes = "'" + loginUser.RoleCodes.Replace(",", "','") + "'";

            var listInfo = query.QueryListData<SysMenuEntity>(string.Format(DataCommandManager.GetSQLCommand("LoadRoleMenus", "SysMenu"),sRoleCodes),null);

            if (listInfo.Count > 0)
            {
                result.Code = 1;
                result.Data = listInfo.MapToList<SysMenuRetDTO>();
                result.Msg = "获取成功！";
            }
            else
            {
                result.Msg = "获取失败！";
            }
            return result;
        }

        /// <summary>
        /// 获取所有的可操作菜单
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<IList<SysMenuRetDTO>> LoadAllMenus()
        {

            var result = new ResultJsonInfo<IList<SysMenuRetDTO>>();
            query.DataBaseName = DatabaseName.GeneralFrameworkDB.GetEnumItemDescription();
            var resultInfo = query.QueryListData<SysMenuEntity>(DataCommandManager.GetSQLCommand("LoadAllMenus", "SysMenu"), null);
            if (resultInfo.Count > 0)
            {
                result.Code = 1;
                result.Data = resultInfo.MapToList<SysMenuRetDTO>();
            }
            else
            {
                result.Msg = "无对应信息！";
            }
            return result;
        }


        ///// <summary>
        ///// 获取所有可操作菜单和菜单下的按钮
        ///// </summary>
        ///// <returns></returns>
        //public ResultJsonInfo<IList<SysMenuEntity>> LoadAllMenuAndButtons()
        //{

        //    var result = new ResultJsonInfo<IList<SysMenuEntity>>();
        //    query.DataBaseName = DatabaseName.MMYoJaDB.GetEnumItemDescription();

        //    var allMenus = query.QueryListData<SysMenuEntity>(DataCommandManager.GetSQLCommand("LoadAllMenus", "SysMenu"), null);

        //    var allButtons = query.QueryListData<SysButtonEntity>(DataCommandManager.GetSQLCommand("LoadAllButtons", "SysMenu"), null).ToList();

        //    foreach (SysMenuEntity item in allMenus)
        //    {
        //        var buttonsList = allButtons.FindAll(r => r.gMenuCode == item.gCode);
        //        if (buttonsList != null && buttonsList.Count > 0)
        //        {
        //            item.buttonList = buttonsList;
        //        }
        //    }
        //    if (allMenus.Count > 0)
        //    {
        //        result.Code = 1;
        //        result.Data = allMenus;
        //    }
        //    else
        //    {
        //        result.Msg = "无对应信息！";
        //    }
        //    return result;
        //}


        ///// <summary>
        ///// 获取所有可操作菜单和菜单下的按钮 及 该角色可操作功能
        ///// </summary>
        ///// <param name="parametersInfo"></param>
        ///// <returns></returns>
        //public ResultJsonInfo<IList<SysMenuEntity>> LoadMenuAndButtonsByRoleCode(ParametersInfo parametersInfo)
        //{

        //    var result = new ResultJsonInfo<IList<SysMenuEntity>>();
        //    string gRoleCode = string.Empty;
        //    if (!string.IsNullOrWhiteSpace(parametersInfo.parameters["sRoleCode"].ToString()))
        //    {
        //        gRoleCode = parametersInfo.parameters["sRoleCode"].ToString();
        //        query.DataBaseName = DatabaseName.MMYoJaDB.GetEnumItemDescription();

        //        //获取所有菜单
        //        var allMenus = query.QueryListData<SysMenuEntity>(DataCommandManager.GetSQLCommand("LoadAllMenus", "SysMenu"), null);

        //        //获取该角色可操作菜单
        //        var myMenus = query.QueryListData<SysRoleMenuEntity>(DataCommandManager.GetSQLCommand("LoadRoleMenusByRoleCode", "SysMenu"), new
        //        {
        //            gRoleCode = gRoleCode
        //        }).ToList();

        //        foreach (SysMenuEntity item in allMenus)
        //        {

        //            var menusList = myMenus.FindAll(r => r.gMenuCode == item.gCode);
        //            if (menusList != null && menusList.Count > 0)
        //            {
        //                item.sChecked = "checked";
        //            }
        //            else
        //            {
        //                item.sChecked = "";
        //            }
        //        }

        //        var allButtons = query.QueryListData<SysButtonEntity>(DataCommandManager.GetSQLCommand("LoadAllButtons", "SysMenu"), null).ToList();

        //        var myButtons = query.QueryListData<SysRoleButtonEntity>(DataCommandManager.GetSQLCommand("LoadRoleButtonsByRoleCode", "SysMenu"), new
        //        {
        //            gRoleCode = gRoleCode
        //        }).ToList();

        //        foreach (SysButtonEntity item in allButtons)
        //        {

        //            var buttonsList = myButtons.FindAll(r => r.gButtonCode == item.gCode);
        //            if (buttonsList != null && buttonsList.Count > 0)
        //            {
        //                item.sChecked = "checked";
        //            }
        //            else
        //            {
        //                item.sChecked = "";
        //            }
        //        }

        //        foreach (SysMenuEntity item in allMenus)
        //        {
        //            var buttonsList = allButtons.FindAll(r => r.gMenuCode == item.gCode);
        //            if (buttonsList != null && buttonsList.Count > 0)
        //            {
        //                item.buttonList = buttonsList;
        //            }
        //        }
        //        if (allMenus.Count > 0)
        //        {
        //            result.Code = 1;
        //            result.Data = allMenus;
        //        }
        //        else
        //        {
        //            result.Msg = "无对应信息！";
        //        }
        //    }

        //    return result;
        //}


        ///// <summary>
        ///// 根据菜单节点code获取菜单下的按钮信息
        ///// </summary>
        ///// <returns></returns>
        //public ResultJsonInfo<IList<SysButtonEntity>> LoadButtons(ParametersInfo parametersInfo)
        //{
        //    var result = new ResultJsonInfo<IList<SysButtonEntity>>();
        //    query.DataBaseName = DatabaseName.MMYoJaDB.GetEnumItemDescription();
        //    excute.DataBaseName = DatabaseName.MMYoJaDB.GetEnumItemDescription();
        //    string menuCode = parametersInfo.parameters["menuCode"].ToString();

        //    var subs = query.QueryListData<SysButtonEntity>(DataCommandManager.GetSQLCommand("LoadButtonByMenuCode", "SysMenu"),
        //                 new { gMenuCode = menuCode });
        //    if (subs.Count > 0)
        //    {
        //        result.Code = 1;
        //        result.Data = subs;
        //        result.Msg = "获取成功！";
        //    }
        //    else
        //    {
        //        result.Code = 1;
        //        result.Msg = "获取失败！";
        //    }
        //    return result;
        //}

        ///// <summary>
        ///// 保存信息
        ///// </summary>
        ///// <returns></returns>
        //public ResultJsonInfo<int> Save(ParametersInfo parametersInfo)
        //{

        //    SysMenuEntity sysMenu = parametersInfo.parameters.ObjectToJSON().JSONToObject<SysMenuEntity>();

        //    var result = new ResultJsonInfo<int>();
        //    query.DataBaseName = DatabaseName.MMYoJaDB.GetEnumItemDescription();
        //    excute.DataBaseName = DatabaseName.MMYoJaDB.GetEnumItemDescription();
        //    int optResult = 0;
        //    #region 功能页面操作
        //    if (string.IsNullOrEmpty(sysMenu.gCode))
        //    {

        //        IList<SysMenuEntity> adminFuns = query.QueryListData<SysMenuEntity>(DataCommandManager.GetSQLCommand("LoadMenusBySort", "SysMenu"),
        //            new { iSort = sysMenu.iSort }
        //         );
        //        foreach (SysMenuEntity item in adminFuns)
        //        {
        //            item.iSort = short.Parse((item.iSort + short.Parse("1")).ToString());
        //            excute.UpdateSingle<SysMenuEntity>(item, " gCode='" + item.gCode + "'");
        //        }
        //        sysMenu.gCode = GuidHelper.GetGuid();
        //        optResult = excute.InsertSingle<SysMenuEntity>(sysMenu);
        //    }
        //    else
        //    {
        //        optResult = excute.UpdateSingle<SysMenuEntity>(sysMenu, " gCode='" + sysMenu.gCode + "'");
        //    }
        //    #endregion

        //    if (optResult > 0)
        //    {
        //        #region 功能页面相关按钮操作
        //        List<SysButtonEntity> newSubs = sysMenu.buttonList;

        //        List<SysButtonEntity> subs = query.QueryListData<SysButtonEntity>(DataCommandManager.GetSQLCommand("LoadButtonByMenuCode", "SysMenu"),
        //            new
        //            {
        //                gMenuCode = sysMenu.gCode
        //            }
        //        ).ToList();

        //        if (subs != null && subs.Count > 0)
        //        {
        //            SysButtonEntity sub = new SysButtonEntity();
        //            foreach (var item in subs)
        //            {
        //                sub = newSubs.Find(p => p.gCode.Contains(item.gCode));
        //                if (sub == null)
        //                {
        //                    excute.UpdateBySQL(DataCommandManager.GetSQLCommand("RemoveButtonByCode", "SysMenu"), new { gCode = item.gCode });
        //                }
        //            }
        //        }

        //        foreach (var item in newSubs)
        //        {
        //            if (!string.IsNullOrWhiteSpace(item.gCode))
        //            {
        //                item.gMenuCode = sysMenu.gCode;
        //                item.sScript = HttpContext.Current.Server.UrlDecode(item.sScript);
        //                optResult = excute.UpdateSingle<SysButtonEntity>(item, " gCode='" + item.gCode + "'");
        //            }
        //            else
        //            {
        //                item.gCode = GuidHelper.GetGuid();
        //                item.gMenuCode = sysMenu.gCode;
        //                item.sScript = HttpContext.Current.Server.UrlDecode(item.sScript);
        //                optResult = excute.InsertSingle<SysButtonEntity>(item);
        //            }
        //        }
        //        #endregion
        //    }
        //    if (optResult > 0)
        //    {
        //        result.Code = 1;
        //        result.Data = optResult;
        //        result.Msg = "菜单信息保存成功！";
        //    }
        //    else
        //    {
        //        result.Msg = "菜单信息保存失败！";
        //    }
        //    return result;
        //}

        ///// <summary>
        ///// 批量删除菜单信息
        ///// </summary>
        ///// <param name="parametersInfo"></param>
        ///// <returns></returns>

        //public ResultJsonInfo<int> batchRemove(ParametersInfo parametersInfo)
        //{

        //    var result = new ResultJsonInfo<int>();
        //    excute.DataBaseName = DatabaseName.MMYoJaDB.GetEnumItemDescription();

        //    string gCodes = parametersInfo.parameters["sCodes"].ToString().Replace("\"", "'").TrimStart('[').TrimEnd(']');

        //    var resultInfo = excute.UpdateBySQL(string.Format(DataCommandManager.GetSQLCommand("BatchRemoveMenus", "SysMenu"), gCodes), null);
        //    if (resultInfo > 0)
        //    {
        //        result.Code = 1;
        //        result.Data = resultInfo;
        //        result.Msg = "批量删除菜单信息成功！";
        //    }
        //    else
        //    {
        //        result.Msg = "批量删除菜单信息失败！";
        //    }
        //    return result;
        //}

        ///// <summary>
        ///// 移动功能
        ///// </summary>
        ///// <param name="flag">上/下移（1：上移/2：下移）</param>
        ///// <param name="id">机构id</param>
        ///// <returns></returns>
        //public ResultJsonInfo<int> move(ParametersInfo parametersInfo)
        //{

        //    int flag = int.Parse(parametersInfo.parameters["flag"].ToString());
        //    string gCode = parametersInfo.parameters["gCode"].ToString();

        //    var result = new ResultJsonInfo<int>();
        //    query.DataBaseName = DatabaseName.MMYoJaDB.GetEnumItemDescription();
        //    excute.DataBaseName = DatabaseName.MMYoJaDB.GetEnumItemDescription();

        //    //（1）所有功能
        //    List<SysMenuEntity> adminFuns = query.QueryListData<SysMenuEntity>(DataCommandManager.GetSQLCommand("LoadAllMenus", "SysMenu"), null).ToList();

        //    //（2）当前功能 
        //    SysMenuEntity currAdminFun = query.QuerySingleData<SysMenuEntity>(DataCommandManager.GetSQLCommand("LoadMenuByCode", "SysMenu"),
        //        new
        //        {
        //            gCode = gCode
        //        });


        //    //（3）当前功能兄弟节点
        //    List<SysMenuEntity> brothersAdminFun = adminFuns.FindAll(r => r.gParentCode == currAdminFun.gParentCode);


        //    SysMenuEntity broAdminFun = null;

        //    foreach (SysMenuEntity item in brothersAdminFun)
        //    {
        //        if (flag == 1)//上移
        //        {
        //            if (item.iSort < currAdminFun.iSort) { broAdminFun = item; }
        //            if (item.iSort > currAdminFun.iSort) { break; } //找到上一个兄弟节点
        //        }
        //        else //下移
        //        {
        //            if (item.iSort > currAdminFun.iSort) { broAdminFun = item; break; } //找到下一个兄弟节点
        //        }
        //    }

        //    List<SysMenuEntity> currFuns = new List<SysMenuEntity>();
        //    currFuns.Add(currAdminFun);
        //    GetMoveNode(adminFuns, currAdminFun.gCode, currFuns);

        //    List<SysMenuEntity> moveFuns = new List<SysMenuEntity>();
        //    moveFuns.Add(broAdminFun);
        //    GetMoveNode(adminFuns, broAdminFun.gCode, moveFuns);

        //    //上移
        //    if (flag == 1)
        //    {
        //        foreach (SysMenuEntity item in currFuns)
        //        {
        //            item.iSort = short.Parse((item.iSort - short.Parse(moveFuns.Count.ToString())).ToString());
        //            excute.UpdateSingle<SysMenuEntity>(item, " gCode='" + item.gCode + "'");
        //        }
        //        foreach (SysMenuEntity item in moveFuns)
        //        {
        //            item.iSort = short.Parse((item.iSort + short.Parse(currFuns.Count.ToString())).ToString());
        //            excute.UpdateSingle<SysMenuEntity>(item, " gCode='" + item.gCode + "'");
        //        }
        //    }
        //    else
        //    {
        //        foreach (SysMenuEntity item in currFuns)
        //        {
        //            item.iSort = short.Parse((item.iSort + short.Parse(moveFuns.Count.ToString())).ToString());
        //            excute.UpdateSingle<SysMenuEntity>(item, " gCode='" + item.gCode + "'");
        //        }
        //        foreach (SysMenuEntity item in moveFuns)
        //        {
        //            item.iSort = short.Parse((item.iSort - short.Parse(currFuns.Count.ToString())).ToString());
        //            excute.UpdateSingle<SysMenuEntity>(item, " gCode='" + item.gCode + "'");
        //        }
        //    }
        //    result.Code = 1;
        //    result.Data = 1;
        //    return result;
        //}

        ///// <summary>
        ///// 上下一定子功能（递归）
        ///// </summary>
        ///// <param name="adminFuns"></param>
        ///// <param name="funId"></param>
        ///// <param name="move"></param>
        //private void GetMoveNode(List<SysMenuEntity> adminFuns, string funId, List<SysMenuEntity> move)
        //{
        //    List<SysMenuEntity> borgs = adminFuns.FindAll(r => r.gParentCode == funId);
        //    foreach (SysMenuEntity item in borgs)
        //    {
        //        if (item.gParentCode == funId)
        //        {
        //            move.Add(item);
        //            List<SysMenuEntity> tempFuns = adminFuns.FindAll(r => r.gParentCode == item.gCode);
        //            if (tempFuns != null && tempFuns.Count > 0)
        //            {
        //                GetMoveNode(adminFuns, item.gCode, move);
        //            }
        //        }
        //    }
        //}
    }
}
